<?php
/**
 * Created by PhpStorm.
 * Date: 2020/11/6
 * Time: 5:29 PM
 */
namespace app\admin\controller;

use app\admin\validate\NodeValidate;
use think\exception\ValidateException;
use think\facade\View;
use app\admin\model\Node as NodeModel;

class Node extends Base
{
    // 节点列表
    public function index()
    {
        $node = new NodeModel();
        $list = $node->getNodesList();

        View::assign([
            'tree' => makeMenuTree($list['data'])
        ]);

        return View::fetch();
    }

    // 添加节点
    public function add()
    {
        if (request()->isPost()) {

            $param = input('post.');

            // 检验完整性
            try {

                validate(NodeValidate::class)->check($param);
            } catch (ValidateException $e) {

                return json(['code' => -1, 'data' => [], 'msg' => $e->getError()]);
            }

            $nodeModel = new NodeModel();
            $param['add_time'] = date('Y-m-d H:i:s');
            $res = $nodeModel->addNode($param);

            return json($res);
        }

        View::assign([
            'pid' => input('param.pid'),
            'pname' => input('param.pname'),
            'menu_type' => config('xcms.menu_type')
        ]);

        return View::fetch();
    }

    // 编辑节点
    public function edit()
    {
        if (request()->isPost()) {

            $param = input('post.');

            // 检验完整性
            try {

                validate(NodeValidate::class)->check($param);
            } catch (ValidateException $e) {

                return json(['code' => -1, 'data' => [], 'msg' => $e->getError()]);
            }

            $nodeModel = new NodeModel();
            $res = $nodeModel->editNode($param);

            return json($res);
        }

        $nodeId = input('param.id');
        $pid = input('param.pid');

        $nodeModel = new NodeModel();
        $nodeInfo = $nodeModel->findNodeInfoById($nodeId);

        if (0 == $pid) {
            $pNode = '顶级节点';
        } else {
            $pNode = $nodeModel->findNodeInfoById($pid)['data']['node_name'];
        }

        View::assign([
            'node_info' => $nodeInfo['data'],
            'pid' => input('param.pid'),
            'p_node' => $pNode,
            'menu_type' => config('xcms.menu_type')
        ]);

        return View::fetch();
    }

    // 删除节点
    public function del()
    {
        if (request()->isAjax()) {

            $id = input('param.id');

            $nodeModel = new NodeModel();
            $res = $nodeModel->deleteNodeById($id);

            return json($res);
        }
    }
}